package com.ego.upload.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UploadServiceImpl implements UploadService{

    private List<String> suffixs = Arrays.asList("png","jpg");
    //磁盘路径
    private String localDir = "D:/EgoCodes/EgoImages/";
    //虚拟地址
    private String urlName = "http://image.ego.com/";
    /**
     * 上传图片
     * @param file
     * @return
     */
    @Override
    public String uploadImage(MultipartFile file) {
        //1,通过文件后缀判断是不是图片(jpg,png..)
        //获取文件名
        String filename = file.getOriginalFilename();
        //截取名称后缀(最后一个小数点后的内容->图片类型)
        String suffix = StringUtils.substringAfterLast(filename, ".");
        if (!suffixs.contains(suffix)){
            return null;
        }
        //2,判断内容是否是图片
        try {
            if(ImageIO.read(file.getInputStream())==null){
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("验证图片出错!");
            return null;
        }
        //实现分目录存储，时间方式
        String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        //定义磁盘文件存储目录
        String dirPath = localDir+dateDir;
        //避免重复上传，动态生成UUID拼接图片名称
        String uuid = String.valueOf(UUID.randomUUID());
        String realFileName = uuid+"."+suffix;
        //3,保存图片到本地磁盘
        try {
            File dir = new File(dirPath);
            if (!dir.exists()){
                dir.mkdirs();
            }

            file.transferTo(new File(dirPath + realFileName));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("保存图片出错!");
            return null;
        }
        //4,拼接路径(http://image.ego.com/xxx.png)
        return urlName+dateDir+realFileName;
    }
}
